from rest_framework.viewsets import ModelViewSet
from meiduo_admin.my_paginate import MyPageNumberPagination
from goods.models import SKUImage,SKU
from . import sku_images_serializers
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from fdfs_client.client import Fdfs_client
from django.conf import settings
from rest_framework import status

#1, skus images
class SKUImagesViewSet(ModelViewSet):
    pagination_class = MyPageNumberPagination
    queryset = SKUImage.objects.all()
    serializer_class = sku_images_serializers.SKUImagesSerializer

    #1,重写create方法,上传图片
    def create(self, request, *args, **kwargs):
        #1,获取参数
        sku_id = request.data.get("sku")
        image = request.FILES.get("image")

        #2,校验参数
        if not all([sku_id,image]):
            return Response("参数不全",status=400)

        #3,数据入库(上传图片)
        client = Fdfs_client(settings.CONFIG_URL) #创建fdfs对象
        result = client.upload_by_buffer(image.read()) #上传图片

        if result["Status"] != "Upload successed.": #判断成功性
            return Response("上传失败", status=400)

        image_url = result["Remote file_id"] #取出图片url

        SKUImage.objects.create(sku_id=sku_id,image=image_url) #创建skuImage对象
        SKU.objects.filter(id=sku_id,default_image_url='').update(default_image_url=image_url) #更新sku默认图片

        #4,返回响应
        return Response(status=status.HTTP_201_CREATED)

    #2,重写updte方法,修改图片
    def update(self, request, *args, **kwargs):
        #1,获取参数
        sku_id = request.data.get("sku")
        image = request.data.get("image")
        sku_image = self.get_object()

        #2,校验参数
        if not all([sku_id,image,sku_image]):
            return Response("参数不全",status=400)

        #3,数据入库(更新图片)
        client = Fdfs_client(settings.CONFIG_URL) #创建fdfs对象
        result = client.upload_by_buffer(image.read()) #上传图片

        if result["Status"] != "Upload successed.": #判断成功性
            return Response("上传失败", status=400)

        image_url = result["Remote file_id"] #取出图片url

        SKUImage.objects.filter(id=sku_image.id,sku_id=sku_id).update(image=image_url)

        #4,返回响应
        return Response(status=status.HTTP_201_CREATED)

#2, skus info
class SKUInfoListView(ListAPIView):
    queryset = SKU.objects.all()
    serializer_class = sku_images_serializers.SKUInfoSerializer